#include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;
#if !defined( unix )
#include <io.h>
#include <fcntl.h>
#endif

double diffclock(clock_t clock1,clock_t clock2)
{
	double diffticks=clock1-clock2;
	double diffms=(diffticks*10)/CLOCKS_PER_SEC;
	return diffms;
}


int main( int argc, char *argv[] ){
    fprintf( stderr, "Run length encoding " );
    if ( argc > 1 ) {
        freopen( argv[ 1 ], "rb", stdin );
        fprintf( stderr, "%s", argv[ 1 ] );
    }else{
        fprintf( stderr, "stdin" );
    }
    fprintf( stderr, " to " );
    if ( argc > 2 ){
        freopen( argv[ 2 ], "wb", stdout );
        fprintf( stderr, "%s", argv[ 2 ] );
    }else{
        fprintf( stderr, "stdout" );
    }
    fprintf( stderr, "\n" );
    
#if !defined( unix )
    setmode( fileno( stdin ), O_BINARY );
    setmode( fileno( stdout ), O_BINARY );
#endif
	clock_t begin=clock();

    short int last_1 = 1;
    short int last_2 = 2;
    short int last_3 = 3;
    short int c;
    while( ( c = getc( stdin ) ) >= 0 ){
        putc( c , stdout );
        if( ( c == last_1 ) && ( c == last_2 ) && ( c == last_3 ) ) {
            short int count = 0;
            while ( count < 255 && ( ( c = getc( stdin ) ) >= 0 ) ) {
                if ( c == last_1 )
                    count++;
                else
                    break;
            }
            putc( count, stdout );
            if( count != 255 && c >= 0 )
                putc( c, stdout );
        }
        last_3 = last_2;
        last_2 = last_1;
        last_1 = c;
    }
    
    clock_t end=clock();
    
    cout << endl << "Start Time: " << double(begin) << " ms"<< endl;
    cout << endl << "End Time: " << double(end) << " ms"<< endl;
    cout << endl << "Time elapsed: " << double(diffclock(end,begin)) << " ms"<< endl;
    return 0;
}
